package com.qf.ability.auth.decorate.impl;

import com.qf.ability.auth.decorate.UserServiceDecorate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;

/**
 * UserDetailsService接口的装饰类
 */
@Service
@Primary
public class UserServiceDecorateImpl implements UserServiceDecorate {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据来源 决定 调用哪一个UserDetailsService
        String fromType = request.getHeader("fromType");
        Assert.notNull(fromType, "fromType must not null");

        UserDetailsService userDetailsService = (UserDetailsService) applicationContext.getBean("userDetailsService" + fromType);
        Assert.notNull(userDetailsService, "fromType not fount duiying de UserDetailsService对象");
        return userDetailsService.loadUserByUsername(username);
    }
}
